const db = require('../config/db')


const sendFn = (res, code, msg, result, total) => {
    // console.log(res)
    res.send({ code, msg, result, total })

}
// sql 封装
const querySql = (res, sql, type = false, value) => {
    let resArr = []
    let resObj = {}

    return new Promise((resolve, reject) => {
        db.query(sql, value, (err, erp) => {
            let resArr = []
            let resObj = {}
            if (err) {
                console.error(`serveError${err}`)
                res.send({ code: 500, msg: `serveError${err}`, })
                return
            }
            if (!type) return resolve(erp)
            resArr = []
            resObj = {}
            erp.forEach(item => {
                resArr = formatToHump(item)
            })
            resolve(resArr)
        })
        // 字符串下划线转驼峰
        const formatToHump = (item) => {
            let resObj = {}
            let KEYS = ''
            for (let KEY in item) {
                KEYS = KEY.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())
                resObj[KEYS] = item[KEY]
            }
            resArr.push(resObj)
            return resArr
        }
    })
}
// 字符串驼峰转下划线
const formatToLine = (item) => {
    let resObj = {}
    let KEYS = ''
    for (let KEY in item) {
        KEYS = KEY.replace(/([A-Z])/g, '_$1').toLowerCase()
        resObj[KEYS] = item[KEY]
    }
    return resObj
}
const intercept = (req, res) => {
    if (!req.body.id) {
        sendFn(res, 1000, '请登录再操作哦')
        return true
    }
    return false
}
module.exports = { sendFn, querySql, intercept, formatToLine } 